package com.ambimmort.shj.service.dpi.users.group;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.common.policy_service.PolicySupport;
import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Dpiusergroup;
import cn.net.greenet.db.bean.UgLink;
import com.ambimmort.umessage.UcType;
import com.ambimmort.umessage.uc.outgoing.vm.x40;
import com.ambimmort.umessage.util.HexUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.util.ArrayList;

/**
 * Created by zyt on 2015/7/31.
 */
@Service
public class LinkService {
    @Autowired
    private SessionFactory hibernateSessionFactory;
    ResultSet rs =null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }

    /**
     *
     * @param json
     * @throws Throwable
     */
    public void linkCreate(String json) throws Throwable{
        JSONObject jsonObj = JSONObject.fromObject(json);
        String groupId = jsonObj.getString("groupId");
        JSONArray links = jsonObj.getJSONArray("links");

        init();
        String sql="select * from dpiusergroup where id="+groupId;
        Object[] params ={};
        rs=baseDao.executeSQL(sql,params);
        try {
            if(!rs.next()){
                String sq="insert into ug_link(DPIUserGroup_id,linkNum)values(?,?)";
                Object[] param ={groupId,links};
                baseDao.executeUpdate(sq,param);
            }
            java.util.List<x40> msgs = new ArrayList<x40>();
            x40.User user = null;
            x40 msg = null;
            for (int i = 0; i < links.size(); i++) {
                if ((i) % 2000 == 0) {
                    msg = new x40();
                    msg.getHeader().setMessageNo(UcType.newUINT4(0));
                    msg.getHeader().setMessageSequenceNo(UcType.newUINT4(0));
                    msg.getHeader().setMessageType(new UcType.UINT1(new byte[]{(byte)0x40}));
                    msg.setAction(UcType.newUINT1(1));
                    msg.setUserGroupName(UcType.newUString_UINT1(rs.getString("name")));
                    msg.setUserGroupNo(UcType.newUINT2(rs.getInt("id")));
                    msg.setMessageSerialNo(UcType.newUINT4(0));
                    msgs.add(msg);
                }
                user = new x40.User();
                user.setUserName(UcType.newUString_UINT1(links.getString(i)));
                user.setUserType(UcType.newUINT1(3));
                msg.getUserNum().add(user);
            }

            // TODO: change the print method to PolicySupport invocation
            for (x40 m : msgs) {
                System.out.println(JSONObject.fromObject(m.toJSON()).toString(4));
                System.out.println(HexUtil.getHex(m.toBytes()));
                String comment = "【"+rs.getInt("id")+"("+rs.getString("name")+")"+"】【link】【＋】【"+links.size()+"】";
                PolicySupport.getInstance().getApi().addPolicy("0x40", rs.getString("instanceName"), m.toJSON(), comment);
            }

//            JSONObject jsonObj = JSONObject.fromObject(json);
//            String groupId = jsonObj.getString("groupId");
//            JSONArray links = jsonObj.getJSONArray("links");
//        Session session = hibernateSessionFactory.openSession();
//        Dpiusergroup bean = (Dpiusergroup) session.get(Dpiusergroup.class, Integer.parseInt(groupId));
//        Transaction tx = session.beginTransaction();
//        try {
//            for (int i = 0; i < links.size(); i++) {
//                UgLink ul = new UgLink(bean);
//                ul.setLinkNum(links.getInt(i));
//                session.saveOrUpdate(ul);
//            }
//            tx.commit();
//            java.util.List<x40> msgs = new ArrayList<x40>();
//            x40.User user = null;
//            x40 msg = null;
//            for (int i = 0; i < links.size(); i++) {
//                if ((i) % 2000 == 0) {
//                    msg = new x40();
//                    msg.getHeader().setMessageNo(UcType.newUINT4(0));
//                    msg.getHeader().setMessageSequenceNo(UcType.newUINT4(0));
//                    msg.getHeader().setMessageType(new UcType.UINT1(new byte[]{(byte)0x40}));
//                    msg.setAction(UcType.newUINT1(1));
//                    msg.setUserGroupName(UcType.newUString_UINT1(bean.getName()));
//                    msg.setUserGroupNo(UcType.newUINT2(bean.getId()));
//                    msg.setMessageSerialNo(UcType.newUINT4(0));
//                    msgs.add(msg);
//                }
//                user = new x40.User();
//                user.setUserName(UcType.newUString_UINT1(links.getString(i)));
//                user.setUserType(UcType.newUINT1(3));
//                msg.getUserNum().add(user);
//            }
//
//            // TODO: change the print method to PolicySupport invocation
//            for (x40 m : msgs) {
//                System.out.println(JSONObject.fromObject(m.toJSON()).toString(4));
//                System.out.println(HexUtil.getHex(m.toBytes()));
//                String comment = "【"+bean.getId()+"("+bean.getName()+")"+"】【link】【＋】【"+links.size()+"】";
//                PolicySupport.getInstance().getApi().addPolicy("0x40", bean.getInstanceName(), m.toJSON(), comment);
//            }

//            out.println("{\"result\":\"true\"}");
        } catch (Exception e) {
            e.printStackTrace();
//            out.println("{\"result\":\"false\"}");
//            tx.rollback();
        } finally {
            close();
//            out.close();
//            session.close();
        }

    }

    /**
     * @param json
     * @throws Throwable
     */
    public void linkDelete(String json) throws Throwable{
        JSONObject jsonObj = JSONObject.fromObject(json);
        String groupId = jsonObj.getString("groupId");
        String instanceName = jsonObj.getString("instanceName");
        JSONArray linkids = jsonObj.getJSONArray("ids");

        java.util.List<x40> msgs = new ArrayList<x40>();
        x40.User user = null;
        x40 msg = null;init();

        init();
        String sql="select * from dpiusergroup where id="+groupId;
        Object[] params ={};
        rs=baseDao.executeSQL(sql,params);
        try {
            UgLink ptr = null;
            Object objPtr = null;
            for (int i = 0; i < linkids.size(); i++) {
                if (rs.next()) {
                    String sq = "delete from ug_link where DPIUserGroup_id=" + groupId+" and linkNum ="+linkids;
                    Object[] param = {};
                    baseDao.executeUpdate(sq, param);
                }
                ptr = (UgLink) objPtr;

                if ((i) % 2000 == 0) {
                    msg = new x40();
                    msg.getHeader().setMessageNo(UcType.newUINT4(0));
                    msg.getHeader().setMessageSequenceNo(UcType.newUINT4(0));
                    msg.getHeader().setMessageType(new UcType.UINT1(new byte[]{(byte) 0x40}));
                    msg.setAction(UcType.newUINT1(2));
                    msg.setUserGroupName(UcType.newUString_UINT1(rs.getString("name")));
                    msg.setUserGroupNo(UcType.newUINT2(rs.getInt("id")));
                    msg.setMessageSerialNo(UcType.newUINT4(0));
                    msgs.add(msg);
                }
                user = new x40.User();
                user.setUserName(UcType.newUString_UINT1(ptr.getLinkNum() + ""));
                user.setUserType(UcType.newUINT1(3));
                msg.getUserNum().add(user);
            }


            for (x40 m : msgs) {
                System.out.println(JSONObject.fromObject(m.toJSON()).toString(4));
                System.out.println(HexUtil.getHex(m.toBytes()));
                String comment = "【"+rs.getInt("id")+"("+rs.getString("name") + ")"+"】【link】【＋】【"+linkids.size()+"】";
                PolicySupport.getInstance().getApi().addPolicy("0x40", rs.getString("instanceName"), m.toJSON(), comment);
            }

//            JSONObject jsonObj = JSONObject.fromObject(json);
//            String groupId = jsonObj.getString("groupId");
//            String instanceName = jsonObj.getString("instanceName");
//            JSONArray linkids = jsonObj.getJSONArray("ids");
//        SessionFactory sf = HibernateUtil.getSessionFactory();
//        Session session = sf.openSession();
//        Transaction tx = session.beginTransaction();
//
//        java.util.List<x40> msgs = new ArrayList<x40>();
//        x40.User user = null;
//        x40 msg = null;
//        Dpiusergroup groupBean = (Dpiusergroup) session.get(Dpiusergroup.class, Integer.parseInt(groupId));

//        try {
//            UgLink ptr = null;
//            Object objPtr = null;
//            for (int i = 0; i < linkids.size(); i++) {
//                objPtr = session.get(UgLink.class, linkids.getInt(i));
//                if (objPtr == null) {
//                    continue;
//                }
//                ptr = (UgLink) objPtr;
//
//                session.delete(ptr);
//                if ((i) % 2000 == 0) {
//                    msg = new x40();
//                    msg.getHeader().setMessageNo(UcType.newUINT4(0));
//                    msg.getHeader().setMessageSequenceNo(UcType.newUINT4(0));
//                    msg.getHeader().setMessageType(new UcType.UINT1(new byte[]{(byte) 0x40}));
//                    msg.setAction(UcType.newUINT1(2));
//                    msg.setUserGroupName(UcType.newUString_UINT1(groupBean.getName()));
//                    msg.setUserGroupNo(UcType.newUINT2(groupBean.getId()));
//                    msg.setMessageSerialNo(UcType.newUINT4(0));
//                    msgs.add(msg);
//                }
//                user = new x40.User();
//                user.setUserName(UcType.newUString_UINT1(ptr.getLinkNum() + ""));
//                user.setUserType(UcType.newUINT1(3));
//                msg.getUserNum().add(user);
//            }
//            tx.commit();
//
//            for (x40 m : msgs) {
//                System.out.println(JSONObject.fromObject(m.toJSON()).toString(4));
//                System.out.println(HexUtil.getHex(m.toBytes()));
//                String comment = "【"+groupBean.getId()+"("+groupBean.getName()+")"+"】【link】【＋】【"+linkids.size()+"】";
//                PolicySupport.getInstance().getApi().addPolicy("0x40", groupBean.getInstanceName(), m.toJSON(), comment);
//            }
//            out.println("{\"result\":\"true\"}");
        } catch (Exception e) {
            e.printStackTrace();
//            out.println("{\"result\":\"false\"}");
//            tx.rollback();
        } finally {
            close();
//            out.close();
//            session.close();
        }
    }


    /**
     *
     * @param iDisplayStart 起始索引
     * @param iDisplayLength 索引条数
     * @param groupId 组id
     * @return
     * @throws Throwable
     */
    public String listLink( String iDisplayStart,String iDisplayLength,String groupId) {
        init();
        try {
            JSONObject json = new JSONObject();
            JSONArray result = new JSONArray();
            Object[] param ={groupId};
            rs=baseDao.executeSQL("select * from ug_link  where DPIUserGroup_id=?",param);

            while (rs.next()){
                JSONArray one = new JSONArray();
                one.add(rs.getInt("DPIUserGroup_id"));
                one.add(rs.getString("linkNum"));
                result.add(one);
            }
            json.put("aaData", result);

//        Session session = hibernateSessionFactory.openSession();
//
//        try {
//            UgLink bean = null;
//            Query q = session.createQuery("SELECT uu FROM UgLink AS uu where uu.dpiusergroup.id=:groupId");
//            q.setParameter("groupId", Integer.parseInt(groupId));
//            q.setMaxResults(Integer.parseInt(iDisplayLength));
//            q.setFirstResult(Integer.parseInt(iDisplayStart));
//
//            java.util.List<UgLink> l = q.list();
//            JSONObject json = new JSONObject();
//            JSONArray result = new JSONArray();
//
//            Query countQuery = session.createQuery("SELECT count(*) FROM UgLink where dpiusergroup.id=:groupId");
//            countQuery.setParameter("groupId", Integer.parseInt(groupId));
//            int length = ((Long) countQuery.iterate().next()).intValue();
//
//            json.put("iTotalRecords", length);
//            json.put("iTotalDisplayRecords", length);
//            int end = Integer.parseInt(iDisplayStart) + Integer.parseInt(iDisplayLength);
//            if (end > length) {
//                end = length;
//            }
//            for (int i = 0; i < l.size(); i++) {
//                bean = (UgLink) l.get(i);
//                JSONArray one = new JSONArray();
//                one.add(bean.getId());
//                one.add(bean.getLinkNum());
//
//                result.add(one);
//            }
//            json.put("aaData", result);

            try {
                return json.toString();
            } catch (Exception e) {
                return "[]";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "[]";
        } finally {
            close();
//            session.close();
        }

    }
}
